package logic

import (
	"context"
	"errors"

	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserFileNameUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserFileNameUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFileNameUpdateLogic {
	return &UserFileNameUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserFileNameUpdateLogic) UserFileNameUpdate(req *types.UserFileNameUpdateRequest, UserIdentity string) (resp *types.UserFileNameUpdateResponse, err error) {
	//判断当前名称在该层级下是否存在
	var count int64
	subQuery := l.svcCtx.DbConn.Select("parent_id").Where("identity=?", req.UserRepositoryIdentity).Table("user_repository")
	err = l.svcCtx.DbConn.Table("user_repository").Where("name=? AND parent_id=(?)", req.FileName, subQuery).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		return nil, errors.New("该名称已存在")
	}
	//修改名称
	err = l.svcCtx.DbConn.Table("user_repository").Where("identity=? AND user_identity=?", req.UserRepositoryIdentity, UserIdentity).
		Update("name", req.FileName).Error
	if err != nil {
		return
	}
	return
}
